package com.jerry.usbserial.fragment.udp

import android.os.Bundle
import android.view.View
import com.espressif.iot.esptouch.util.ByteUtil
import com.espressif.iot.esptouch.util.TouchNetUtil
import com.jerry.usbserial.R
import com.jerry.usbserial.util.InputFilterMinMax
import com.jerry.usbserial.util.hideSoftInput
import com.jerry.usbserial.util.showToast
import com.jerry.usbserial.util.task.udp.SmartConnectTask
import com.jerry.usbserial.util.to4HByteArray
import kotlinx.android.synthetic.main.bar_common.*
import kotlinx.android.synthetic.main.frg_one_click.*


/**
 * Created by dugang on 2020/7/5.
 */
class SmartConnectFragment : UdpFragment() {
    private var mTask: SmartConnectTask? = null

    override val layoutId: Int = R.layout.frg_one_click


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        toolbar_title.text = "一键配网"

        bt_start.setOnClickListener {
            hideSoftInput()
            if (tv_ssid.text.isEmpty()) {
                mContext.showToast("WIFI 不可用")
                return@setOnClickListener
            }
            if (et_password.text.isEmpty()) {
                mContext.showToast("请输入 WIFI 密码")
                return@setOnClickListener
            }

            val ssid = ByteUtil.getBytesByString(tv_ssid.text.toString())
            val bssid = TouchNetUtil.parseBssid2bytes(tv_bssid.text.toString())
            val password = ByteUtil.getBytesByString(et_password.text.toString())

            mTask?.cancelEsptouch()
            mTask = SmartConnectTask(mContext) { mTask = null }.apply {
                execute(ssid, bssid, password,"1".toByteArray() , 0.to4HByteArray())
            }
        }
    }

    override fun handlerResult(ssid: String?, bssid: String?, ip: String?, error: String?) {
        tv_ssid.text = ssid
        tv_bssid.text = bssid
        tv_message.text = error
    }
}